﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyTouchManage : MonoBehaviour
{
    private Camera uiCamera;
    // Start is called before the first frame update
    void Start()
    {
        for (int i = 0; i < Camera.allCamerasCount; i++)
        {
            Camera camera = Camera.allCameras[i];
            if (camera.gameObject.layer == LayerMask.NameToLayer("UI"))
            {
                uiCamera = camera;
                break;
            }
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (Application.platform == RuntimePlatform.WindowsEditor)
        {
            if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
            {
                Ray ray = uiCamera.ScreenPointToRay(Input.mousePosition);
                RaycastHit hit;

                if (Physics.Raycast(ray, out hit))
                {
                    MyTouch myTouch = hit.transform.GetComponent<MyTouch>();
                    if (myTouch != null)
                    {
                        Touch touch = new Touch();
                        touch.position = Input.mousePosition;
                        touch.phase = Input.GetMouseButtonDown(0) ? TouchPhase.Began : Input.GetMouseButtonUp(0) ? TouchPhase.Ended : TouchPhase.Moved;
                        myTouch.touch = touch;
                        myTouch.isInUpdate = true;
                    }
                }
            }
        }
        else
        {
            for (int i = 0; i < Input.touchCount; i++)
            {
                Touch touch = Input.GetTouch(i);
                Ray ray = uiCamera.ScreenPointToRay(touch.position);

                RaycastHit hit;

                if (Physics.Raycast(ray, out hit))
                {
                    MyTouch myTouch = hit.transform.GetComponent<MyTouch>();
                    if (myTouch != null)
                    {
                        myTouch.touch = touch;
                        myTouch.isInUpdate = true;
                    }
                }
            }
        }
    }
}
